package whoever;

import org.bouncycastle.math.ec.ECPoint;

import java.io.IOException;
import java.math.BigInteger;

/**
 * 函数的测试和示范
 */
public class TestFunction {

    public static void main(String[] args) throws IOException {
        // SM3杂凑算法
        System.out.println("————————SM3杂凑算法演示————————");
        String m = "你好";
        System.out.println("message:" + m);
        String hashOfM = SM3.byteArrayToHexString(SM3.hash(m.getBytes()));
        System.out.println("hash:" + hashOfM);

        // SM2椭圆曲线加密算法
        System.out.println("————————SM2椭圆曲线加密算法演示————————");
        SM2 sm2 = new SM2();

        // 生成密钥对
        SM2KeyPair myKeyPair = sm2.generateKeyPair();
        // 公钥
        ECPoint publicKey = myKeyPair.getPublicKey();
        System.out.println("生成的公钥是:");
        SM2.printHexString(myKeyPair.getPublicKey().getEncoded(false));
        // String类型的公钥
        String publicKeyInString = SM2.getPublicKeyInString(publicKey);
        // 将String类型的公钥转化为ECPoint类型
        ECPoint publicKeyInECPoint = SM2.getPublicKeyInECPoint(publicKeyInString);
        // 私钥
        BigInteger privateKey = myKeyPair.getPrivateKey();
        System.out.println("生成的私钥是:");
        System.out.println(myKeyPair.getPrivateKey().toString());
        // String类型的私钥
        String privateKeyInString = SM2.getPrivateKeyInString(privateKey);
        // 将String类型的私钥转化为BigInteger类型
        BigInteger privateKeyInBigInteger = SM2.getPrivateKeyInBigInteger(privateKeyInString);

        // 加解密过程
        byte[] data = sm2.encrypt("测试加密", myKeyPair.getPublicKey());
        System.out.println("密文：");
        SM2.printHexString(data);
        String message = sm2.decrypt(data, myKeyPair.getPrivateKey());
        System.out.println("明文：");
        System.out.println(message);

        // 导出密钥到本地过程
        String publicKeyPath = "E:/Key/publicKey";
        sm2.exportPublicKey(myKeyPair.getPublicKey(), publicKeyPath);
        String privateKeyPath = "E:/Key/privateKey";
        sm2.exportPrivateKey(myKeyPair.getPrivateKey(), privateKeyPath);

        // 从本地导入密钥的过程
        ECPoint importedPublicKey = sm2.importPublicKey(publicKeyPath);
        System.out.println("导入的公钥是:");
        SM2.printHexString(importedPublicKey.getEncoded(false));
        BigInteger importedPrivateKey = sm2.importPrivateKey(privateKeyPath);
        System.out.println("导出的私钥是:");
        System.out.println(importedPrivateKey.toString());

        // 签名与验签过程
        String IDA = "用户A";
        String M = "你好";
        SM2.Signature signature = sm2.sign(M, IDA, myKeyPair);
        System.out.println("用户标识:" + IDA);
        System.out.println("签名信息:" + M);
        System.out.println("数字签名:" + signature);
        System.out.println("验证签名:" + sm2.verify(M, signature, IDA, myKeyPair.getPublicKey()));
    }
}
